#include <string.h>
#include <stdio.h>
#include <pthread.h>
#include <unistd.h>

#include "data_unit.h"
#include "ipcclient.h"
#include "cmd.h"
#include "data_integrity.h"

#define IPCFILE "/tmp/ftr_ipc_test"

void *__client_notify(void *param) {
    pipcclient_t pipcclient = (pipcclient_t)param;

    pipcclient->loop(pipcclient);

    return NULL;
}

int __server_reponse(void *handler, unsigned char *buf, unsigned int buf_len, void *param){
    printf("%s\n", buf);

    return 0;
}

int main(int argc, char **argv) {

    pcmd_t pcmd = NULL;
    pipcclient_t pipcclient = NULL;
    pdi_t pdi = NULL;
    dataunit_t du_response = {0};

    du_next_unit_init(&du_response);
    du_response.recv = __server_reponse;
    
    cmd_alloc(&pcmd);
    ipcclient_alloc(&pipcclient);
    di_alloc(&pdi, 200);
    
    pcmd->init(pcmd);
    pipcclient->init(pipcclient, IPCFILE);

    du_chain_t send_chain[] = {        
        {(pdataunit_t)pcmd, DATAUNIT_DIRECT_NONE, DATAUNIT_DIRECT_NONE},
        {(pdataunit_t)pdi, DATAUNIT_DIRECT_NONE, DATAUNIT_DIRECT_SEND},
        {(pdataunit_t)pipcclient, DATAUNIT_DIRECT_NONE, DATAUNIT_DIRECT_SEND},
    };

    du_chain_t recv_chain[] = {
        {(pdataunit_t)pipcclient, DATAUNIT_DIRECT_NONE, DATAUNIT_DIRECT_NONE},
        {(pdataunit_t)pdi, DATAUNIT_DIRECT_RECV, DATAUNIT_DIRECT_NONE},
        {(pdataunit_t)&du_response, DATAUNIT_DIRECT_RECV, DATAUNIT_DIRECT_NONE},
    };
    
    du_chain_init(send_chain, sizeof(send_chain)/sizeof(send_chain[0]));
    du_chain_init(recv_chain, sizeof(recv_chain)/sizeof(recv_chain[0]));

    pthread_t id;
    pthread_create(&id, NULL, __client_notify, (void*)pipcclient);

    while(pipcclient->status != IPCCLIENT_STATUS_CONNECT) {
        printf("wait connect\n");
        sleep(1);
    }
    
    pdataunit_t writecmd = (pdataunit_t)pcmd;
    writecmd->send(writecmd, (unsigned char*)"/bin/ls -l", strlen("/bin/ls -l"), NULL);

   sleep(1);
    
    pcmd->deinit(pcmd);
    pipcclient->deinit(pipcclient);
    
    
    di_dealloc(&pdi);
    cmd_dealloc(&pcmd);
    ipcclient_dealloc(&pipcclient);
    return 0;
    
}
